package me.zhengjie.modules.system.rest

import me.zhengjie.common.exception.BadRequestException
import me.zhengjie.logging.annotation.Log
import me.zhengjie.modules.system.domain.*
import me.zhengjie.modules.system.service.DictService
import me.zhengjie.modules.system.service.dto.DictQueryCriteria
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.servlet.http.HttpServletResponse
import org.springframework.data.domain.Pageable
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import java.io.IOException

/**
 * @author Kuki Wu
 * @date 2019-04-10
 */
@Schema(description = "系统：字典管理")
@RestController
@RequestMapping("/api/dict")
class DictController(private val dictService: DictService) {
    @Log("导出字典数据")
    @Schema(description = "导出字典数据")
    @GetMapping(value = ["/download"])
    @PreAuthorize("@el.check('dict:list')")
    @Throws(
        IOException::class
    )
    fun download(response: HttpServletResponse?, criteria: DictQueryCriteria?) {
        dictService.download(dictService.queryAll(criteria!!), response)
    }

    @Log("查询字典")
    @Schema(description = "查询字典")
    @GetMapping
    @PreAuthorize("@el.check('dict:list')")
    fun getDicts(resources: DictQueryCriteria?, pageable: Pageable?): ResponseEntity<*> {
        return ResponseEntity(dictService.queryAll(resources!!, pageable), HttpStatus.OK)
    }

    @Log("新增字典")
    @Schema(description = "新增字典")
    @PostMapping
    @PreAuthorize("@el.check('dict:add')")
    fun create(@Validated @RequestBody resources: Dict): ResponseEntity<*> {
        if (resources.id != null) {
            throw BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID")
        }
        return ResponseEntity(dictService.create(resources), HttpStatus.CREATED)
    }

    @Log("修改字典")
    @Schema(description = "修改字典")
    @PutMapping
    @PreAuthorize("@el.check('dict:edit')")
    fun update(
        @Validated(
            Dict.Update::class
        ) @RequestBody resources: Dict?
    ): ResponseEntity<*> {
        dictService.update(resources!!)
        return ResponseEntity<Any?>(HttpStatus.NO_CONTENT)
    }

    @Log("删除字典")
    @Schema(description = "删除字典")
    @DeleteMapping(value = ["/{id}"])
    @PreAuthorize("@el.check('dict:del')")
    fun delete(@PathVariable id: Long?): ResponseEntity<*> {
        dictService.delete(id!!)
        return ResponseEntity<Any?>(HttpStatus.OK)
    }

    companion object {
        private const val ENTITY_NAME = "dict"
    }
}